package com.xiaohe66.demo.rabbitmq.spring;

import com.xiaohe66.demo.rabbitmq.Const;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xiaohe
 * @time 2021.06.18 16:18
 */
@Configuration
@RequiredArgsConstructor
@Slf4j
public class TopicConfig implements InitializingBean {

    private final AmqpAdmin amqpAdmin;

    @RabbitListener(queues = Const.SPRING_TOPIC_QUEUE_A)
    public void rabbitmqListener(Message message) {

        MessageProperties properties = message.getMessageProperties();

        log.info("topic A 监听到第{}条消息 : {}", properties.getDeliveryTag(), new String(message.getBody()));
    }

    @RabbitListener(queues = Const.SPRING_TOPIC_QUEUE_B)
    public void rabbitmqListenerB(Message message) {

        if (log.isInfoEnabled()) {

            MessageProperties properties = message.getMessageProperties();

            log.info("topic B 监听到第{}条消息 : {}", properties.getDeliveryTag(), new String(message.getBody()));
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        log.info("初始化交换机和队列 start");

        amqpAdmin.declareExchange(new TopicExchange(Const.SPRING_TOPIC_EXCHANGE, true, false));

        amqpAdmin.declareQueue(new Queue(Const.SPRING_TOPIC_QUEUE_A, true));
        amqpAdmin.declareQueue(new Queue(Const.SPRING_TOPIC_QUEUE_B, true));

        // routingKey :  * 匹配一个单词，# 匹配多个单词
        amqpAdmin.declareBinding(new Binding(Const.SPRING_TOPIC_QUEUE_A, Binding.DestinationType.QUEUE, Const.SPRING_TOPIC_EXCHANGE, "topic.a.*", null));
        amqpAdmin.declareBinding(new Binding(Const.SPRING_TOPIC_QUEUE_B, Binding.DestinationType.QUEUE, Const.SPRING_TOPIC_EXCHANGE, "topic.b.#", null));

        log.info("初始化交换机和队列 end");
    }
}
